package com.cmict.data.form.api.util.SubUtil;

import cn.hutool.core.util.ObjectUtil;
import com.cmict.data.framework.common.pojo.CommonResult;
import com.cmict.data.form.api.service.SysCurrencyService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.cmict.data.framework.common.pojo.CommonResult.success;

/**
 * @description: el-input组件规则
 * @author: qiaoyu
 * @create: 2022-07-18 22:57
 **/
public class ElCascaderUtil {

	@Resource
	private static SysCurrencyService sysCurrencyService;

	public static CommonResult rule (JSONObject personData , String value , int number) {
		String message = "";
		Boolean redata = true;
		JSONArray fields = personData.getJSONArray("fields");
		JSONObject field = fields.getJSONObject(number);
		JSONObject config = field.getJSONObject("__config__");
		String label = config.getString("label");
		//是否必填
		Boolean required = config.getBoolean("required");
		if(required && ObjectUtil.isEmpty(value)){
			message = label+"是必填项;";
			redata=false;
			//return success( label+"是必填项",false);
		}
		String datatype = field.getString("dataType");
		if("static".equals(datatype)){
			JSONArray optionsList = field.getJSONArray("options");
			List<String> result = new ArrayList<>();
			get(optionsList, "", result);
			if(!result.contains(value)){
				message = message + label+"请在"+result+"中选择数据;";
				redata=false;
			}
		}
		if("datasource".equals(datatype)){
			JSONArray optionsList = field.getJSONArray("fields");
			List<String> result = new ArrayList<>();
			get(optionsList, "", result);
			if(!result.contains(value)){
				message = message + label+"请在"+result+"中选择数据;";
				redata=false;
			}
		}
		if(!redata){
			return success( message,false);
		}
		return success( "通过",true);
	}


	private static void get(JSONArray optionsList, String preName, List<String> result) {
		String name ="";
		for (int i = 0; i <optionsList.size() ; i++) {
			String namei = optionsList.getJSONObject(i).getString("label");
			if (StringUtils.isBlank(preName)) {
				name=namei;
			} else {
				name=preName+"/"+namei;
			}
			JSONArray childrens = optionsList.getJSONObject(i).getJSONArray("children");
			if (ObjectUtil.isNotEmpty(childrens)){
				get(childrens, name, result);
			} else {
				result.add(name);
			}
		}
	}
}

